package org.znxs.comfriend.activities;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import org.znxs.comfriend.R;
import org.znxs.comfriend.adapters.MessageAdapter;
import org.znxs.comfriend.models.Message;
import org.znxs.comfriend.models.User;
import org.znxs.comfriend.utils.AllUserList;
import org.znxs.comfriend.utils.LoginUser;

import java.util.List;
import java.util.Map;

public class ChatActivity extends AppCompatActivity {


    private ImageView ivReceiverAvatar;
    private TextView tvReceiverName;
    private RecyclerView recyclerViewMessages;
    private EditText etMessage;
    private Button btnSend;

    private MessageAdapter messageAdapter;
    private LoginUser loginUser;

    private User receiverUser = new User();

    private AllUserList allUserList = AllUserList.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_messaging); // 设置布局文件

        // 初始化当前登录用户
        loginUser = LoginUser.getInstance(this);

        // 初始化视图
        ivReceiverAvatar = findViewById(R.id.iv_receiver_avatar);
        tvReceiverName = findViewById(R.id.tv_receiver_name);
        recyclerViewMessages = findViewById(R.id.recycler_view_messages);
        etMessage = findViewById(R.id.et_message);
        btnSend = findViewById(R.id.btn_send);

        // 获取传递的用户信息

        receiverUser.setId(getIntent().getStringExtra("receiverUserId"));
        receiverUser.setNickname(getIntent().getStringExtra("receiverUserName"));
        receiverUser.setAvatarUrl(getIntent().getStringExtra("receiverUserAvatarUrl"));

        // 设置接收者信息
        Glide.with(this)
                .load(receiverUser.getAvatarUrl())
                .placeholder(R.drawable.pengyiyan)
                .error(R.drawable.error)
                .into(ivReceiverAvatar);

        tvReceiverName.setText(receiverUser.getNickname());

        // 初始化消息适配器
        recyclerViewMessages.setLayoutManager(new LinearLayoutManager(this));
        messageAdapter = new MessageAdapter(this, receiverUser.getId());
        recyclerViewMessages.setAdapter(messageAdapter);

        // 添加测试数据到 loginUser.messageHashMap
        String senderId = loginUser.getLoginUser().getId();
        String receiverId = receiverUser.getId();
        Map<String, List<Message>> messageHashMap = loginUser.getLoginUser().getMessageHashMap();
        if (messageHashMap.isEmpty()) {
            loginUser.addMessage(receiverId, senderId, "Hello!", System.currentTimeMillis());
            loginUser.addMessage(receiverId, receiverId, "Hi there!", System.currentTimeMillis());
            loginUser.addMessage(receiverId, senderId, "How are you?", System.currentTimeMillis());
        }


        // 刷新适配器
        messageAdapter.refreshMessages(receiverUser.getId()); // 调用适配器的刷新方法

        // 发送按钮点击事件
        btnSend.setOnClickListener(v -> sendMessage(receiverId));
        // 为接收者头像添加点击事件
        ivReceiverAvatar.setOnClickListener(v -> {
            Intent intent = new Intent(this, FriendDetailActivity.class);
            User user = allUserList.getUserById(receiverUser.getId());
            if (user != null) {
                intent.putExtra("user", user);
                startActivity(intent);
            }
        });
    }


    /**
     * 发送消息
     */
    private void sendMessage(String receiverId) {
        String messageText = etMessage.getText().toString().trim();
        if (!TextUtils.isEmpty(messageText)) {
            // 获取当前时间戳
            long timestamp = System.currentTimeMillis();

            // 创建消息对象并存储到 loginUser.messageHashMap 中
            String senderId = loginUser.getLoginUser().getId();
            loginUser.addMessage(receiverId, senderId, messageText, timestamp);

            // 刷新适配器
            messageAdapter.refreshMessages(receiverId);
            recyclerViewMessages.scrollToPosition(messageAdapter.getItemCount() - 1);

            // 清空输入框
            etMessage.setText("");

        }
    }

}